<template>
    <div class="mark">
        <div class="left">
            <el-scrollbar class="scrollbar-demo-item">
                <el-tree
                        style="width: 240px; height: 75vh"
                        :data="data"
                        default-expand-all
                        @node-click="nodeClick"
                        :props="props"
                        :loading="loading"
                />
            </el-scrollbar>
        </div>
        <div class="right">

            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="课程" name="课程">
            <v-md-editor v-model="text" height="70vh" mode="preview" options="{ toc: true }"/>
        </el-tab-pane>
        <el-tab-pane label="作业" name="作业">
            <ClassWork v-if="activeName=='作业'" :data="nodeData" :classId="formData.classId" :permissions="permissions" />
        </el-tab-pane>
      </el-tabs>

            
            <el-tooltip content="结束班级课程" placement="left" effect="dark">
                <el-button class="classCourse" :icon="Check" type="success" @click="classCourse" circle />
            </el-tooltip>
            <el-tooltip content="跳转到课程维护页面" placement="left" effect="dark">
                <el-button class="buttonCourse" type="primary" :icon="Edit" @click="goCourse" circle />
            </el-tooltip>

        </div>
    </div>
</template>


<script setup>
    import { ref ,onMounted} from "vue";
    import axios from "@/axios/index.js";
    import { reactive } from "@vue/reactivity";
    import {Edit,Notebook,Check} from '@element-plus/icons-vue'
    import {ElMessage, ElMessageBox} from "element-plus";
    import { useRouter} from 'vue-router';
import ClassWork from "./ClassWork.vue";

    const text = ref("");
    // 课程ID定义为响应式数据
    const courseId = ref("");

    let loading = ref(true);

    // 课程数据
    let data = ref([]);
    // 课程信息数据
    let data1 = ref([]);

    let permissions = ref()
    // 对已经学过的课程变灰处理
    const customNodeClass = (data, node) => {
        if (data.finished) {
            return "finished";
        }
        return "unfinished";
    };

    console.log()

    const props = {
        label: "courseName",
        children: "children",
        isLeaf: "leaf",
        class: customNodeClass
    };

    let classWork = ref(null)

    let currentCourseData = reactive()

    const nodeData = ref({})

    const activeName = ref("课程")

    const handleClick = (event) => {
  activeName.value = event.props.name
}

    // 课程点击事件
    const nodeClick = (node) => {

        currentCourseData = node
        
        text.value = node.courseContent
        // 获取课程ID
        courseId.value = node.id;
        formData.courseId = courseId.value;
        // console.log(courseId.value)
        nodeData.value = node
  if (activeName.value === '作业') {
    if (classWork.value) {
      // 直接调用子组件的方法
      classWork.value.loadTableData();
    }
  }
    };

    let formData = reactive({
        classId: '',
        courseId: '',
        subjectId: ''
    })
    const router = useRouter();
    onMounted(async () => {
        const { classId, subjectId, isPermissions} = router.currentRoute.value.query;
        formData.classId = classId;
        formData.subjectId = subjectId;
        await classProgress();
        await loadTableData();

      permissions.value = isPermissions;
      console.log(isPermissions)
    });

    // 获取班级的所有课程
    async function  loadTableData() {
        loading.value = true;
        axios.get("api/v1/admin/course/selectCourseByClassId",{params:{
                classId:formData.classId,
            }}).then((resp) => {
                // console.log(resp);
            data1 = resp.data.data
            axios.get("api/v1/admin/course/selectAllCourseByClassId",{params:{
                classId:formData.classId,
                pid:0,
                status:1,
                subjectId:formData.subjectId
            }}).then((resp) => {
            loading.value = false;
            data = resp.data.data
            // console.log(data)
            compareCourseProgress()
        });
        })
    }
    // onMounted(()=>{
    //     loadTableData()
    // })

    // 获取班级课程进度
    async function classProgress() {
        // console.log('classProgress函数开始，formData.classId:', formData.classId);
        await axios.get("api/v1/admin/course/selectCourseByClassId",{params:{
                classId:formData.classId,
            }}).then((resp) => {
            // console.log(resp.data.data)
            data1 = resp.data.data
        });
    }

    // 对比进度进行变色处理
    function compareCourseProgress() {
        function checkCourseFinished(course) {
            const isFinished = data1.some((progressCourse) => progressCourse.id === course.id);
            course.finished = isFinished;
            // console.log(isFinished)
            // console.log(course.id)
            if (course.children) {
                course.children.forEach(childCourse => checkCourseFinished(childCourse));
            }
        }
        data.forEach(course => checkCourseFinished(course));
    }

    // 结束班级的课程，将班级的Id和课程Id添加到班级进度表
    function classCourse(){
      console.log(typeof  permissions.value)

      if (permissions.value == 0){
        ElMessage({
          message: '无权操作',
          type: 'warning',
        })
        return;
      }

        if (!courseId.value) {
            ElMessageBox({
                type: 'warning',
                message: '请选择要结束的课程',
            });
            return;
        }
        ElMessageBox.confirm(
            '是否结束此课程',
            '警告',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
        )
        .then(() => {
            axios.post('/api/v1/admin/classCourseProgress/insert',formData).then((resp) => {
                ElMessage({
                    message: "已结束此课程" ,
                    message: resp.data.message,
                    type: 'success',
                    duration: 1500,
                    
                });
                compareCourseProgress()
                classProgress()
                loadTableData()
              });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消此操作',
            });
        });
    }
    // classProgress();

    // loadTableData();

    // 跳转到课程维护页面
    function goCourse() {
        window.location.href = '/course';
    }

</script>

<style scoped>
    .mark {
        display: flex;
    }
    .left {
        width: 300px;
        padding: 20px;
        height: 100%;
        border-right: 1px solid #bbbbbb;
        box-sizing: border-box;
        background-color: #fff;
    }

    .form {
        display: flex;
        justify-content: center;
    }

    .right {
        width: 1400px;
        position: relative;
    }
    .scrollbar-demo-item {
        display: flex;
        border-radius: 4px;
        color: var(--el-color-primary);
    }
    .buttonCourse{
        position: absolute;
        bottom: 20px;
        right: 20px;
    }
    .classCourse{
        position: absolute;
        bottom: 80px;
        right: 20px;
    }
    .v-md-toc {
        background-color: #f9f9f9;
        font-family: Arial, sans - serif;
        margin-right: 10px;
    }
    ::v-deep .el-tabs__nav-scroll {
  margin-left: 20px;
}
</style>